package com.rjkj.medicalwaste.ui.storage

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.databinding.DialogUserCodeBinding
import com.rjkj.medicalwaste.databinding.FragmentScanUserBinding
import com.rjkj.medicalwaste.databinding.FragmentStorageFunctionBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider


class ScanUserFragment : BaseFragment<FragmentScanUserBinding>() {
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentScanUserBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        return binding.root
    }
    override fun dealCustomScanData(data: String) {
        super.dealCustomScanData(data)
        doScanCode(data,null)
    }
    override fun onSubscribeUi(binding: FragmentScanUserBinding) {
        binding.imClose.setOnClickListener {
            requireActivity().onBackPressed()
        }
        binding.pic.setOnClickListener {
            scanWithCustomUI()
        }
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner,
        ) {
            doScanCode(it, binding)
        }
    }

    private fun doScanCode(
        it: String,
        binding: FragmentScanUserBinding?
    ) {
        userViewModel.checkLogin(it).observe(viewLifecycleOwner, { user ->
            if (user != null) {
                if(binding!=null){
                    binding.tvName.text = user.name
                }
                userViewModel.uploadUser.value = user
                findNavController().navigateUp()
            } else {
                if(binding!=null){
                    binding.tvName.text = "未找到清理人"
                }
            }
        })
    }

}